package com.nuanshui.heatedloan.fund.biz.service;

import com.nuanshui.framework.consts.TransactionManagerType;
import com.nuanshui.framework.lang.SysStringUtils;
import com.nuanshui.framework.utils.LogUtil;
import com.nuanshui.heatedloan.baseservice.service.CommonServiceImpl;
import com.nuanshui.heatedloan.fund.biz.dal.mapper.PayPasswordMapper;
import com.nuanshui.heatedloan.fund.facade.PayPasswordService;
import com.nuanshui.heatedloan.fund.model.PayPassword;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(value=TransactionManagerType.FUND_TRANSACTION_MANAGER)
public class PayPasswordServiceImpl extends CommonServiceImpl implements PayPasswordService{

	@Autowired
	private PasswordEncoder pwdEncoder;

	@Autowired
	private PayPasswordMapper payPasswordMapper;

	private static final Logger  logger = LoggerFactory.getLogger("pay_password");

	@Override
	@Transactional(value=TransactionManagerType.FUND_TRANSACTION_MANAGER)
	public void setPayPassword(String password, String currentUserId) {
		if (password.length()!=6) error("请输入6位的数字密码。");
		PayPassword payPassword = new PayPassword();
		payPassword.setPayPassword(pwdEncoder.encode(password));
		payPassword.setUserId(currentUserId);
		payPasswordMapper.insert(payPassword);
		LogUtil.info(logger, "设置支付密码成功。。。。。。");
	}
	
	@Override
	@Transactional(value=TransactionManagerType.FUND_TRANSACTION_MANAGER)
	public void emptyUserPayPassword(String currentUserId) {
		payPasswordMapper.updatePayPasswordNull(currentUserId);
	}

	@Override
	public boolean isSetPayPassword(String currentUserId) {
		LogUtil.info(logger, "正在查询是否设置支付密码。。。。。。");
		PayPassword payPassword = payPasswordMapper.getByUserId(currentUserId);
        return payPassword != null;
	}

	@Override
	public boolean verifyPayPassword(String password, String currentUserId) {
		LogUtil.info(logger, "正在校验支付密码。。。。。。");
		if (!SysStringUtils.isEmpty(password)) {
			String pwd = payPasswordMapper.findPasswordByUserId(currentUserId);
			if (pwdEncoder.matches(password, pwd)) {
				return true;
			}
		}
		return false;
	}

	@Override
	@Transactional(value=TransactionManagerType.FUND_TRANSACTION_MANAGER)
	public void changePayPassword(String password, String currentUserId) {
		//password = commonTool.decryptPassword(getUserAgent().getSafeToken(), password);
		if (SysStringUtils.isEmpty(password)) error("请输入新的支付密码");
		if (password.length()!=6) error("请输入6位的数字密码。");
		payPasswordMapper.updatePayPassword(currentUserId, pwdEncoder.encode(password));
		LogUtil.info(logger, "支付密码修改成功。。。。。。");
	}
	
}
